package org.bigdata.framework.core.utils;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.QueryOperators;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

/**
 * mongodb工具类 (增删改-单个/批量方法)
 * 
 * @author anhuifeng
 * 
 */
public class MongoClientUtils {

	public static MongoDatabase mongoDatabase = null;
	public static MongoClient mongoClient = null;

	// 打开连接
	public static MongoDatabase getMongoDatabaseConnection(String host,
			int port, String databaseName) {
		if (mongoDatabase == null) {
			mongoClient = new MongoClient(host, port);
			mongoDatabase = mongoClient.getDatabase(databaseName);
		}
		return mongoDatabase;
	}

	// 关闭连接
	public static void closeConnection() {
		if (mongoClient != null) {
			mongoClient.close();
			mongoClient = null;
			mongoDatabase = null;
		}
	}

	// 批量插入
	public static void insertMany(MongoDatabase mongoDatabase,
			String collection, List<Document> documents) {
		MongoCollection<Document> coll = mongoDatabase
				.getCollection(collection);
		coll.insertMany(documents);
	}

	// 单条插入
	public static void insertOne(MongoDatabase mongoDatabase,
			String collection, Document document) {
		MongoCollection<Document> coll = mongoDatabase
				.getCollection(collection);
		coll.insertOne(document);
	}

	// 单个编辑数据
	public static void edit(MongoDatabase mongoDatabase, String collection,
			String id, Map<String, Object> dynamicData) {
		MongoCollection<Document> coll = mongoDatabase
				.getCollection(collection);
		coll.updateOne(new Document("id", id), new BasicDBObject("$set",
				dynamicData));
	}

	// 批量编辑数据
	public static void editByIds(MongoDatabase mongoDatabase,
			String collection, String[] ids, Map<String, Object> dynamicData) {
		MongoCollection<Document> coll = mongoDatabase
				.getCollection(collection);
		// coll.updateMany(new BasicDBObject("$in",ids), new
		// BasicDBObject("$set",dynamicData));
		coll.updateMany(Filters.in("id", ids), new BasicDBObject("$set",
				dynamicData));
	}

	// 批量编辑数据
	public static void edit(MongoDatabase mongoDatabase, String collection,
			Map<String, Object> conditions, Map<String, Object> dynamicData) {
		MongoCollection<Document> coll = mongoDatabase
				.getCollection(collection);
		coll.updateMany(new BasicDBObject(conditions), new BasicDBObject(
				"$set", dynamicData));
	}

	// 单个删除数据
	public static void delete(MongoDatabase mongoDatabase, String collection,
			String id) {
		MongoCollection<Document> coll = mongoDatabase
				.getCollection(collection);
		coll.deleteOne(new Document("id", id));
	}

	// 批量删除数据
	public static void delete(MongoDatabase mongoDatabase, String collection,
			Map<String, Object> conditions) {
		MongoCollection<Document> coll = mongoDatabase
				.getCollection(collection);
		coll.deleteMany(new BasicDBObject(conditions));
	}

	// 查询单个数据
	public static Document find(MongoDatabase mongoDatabase, String collection,
			String id) {
		MongoCollection<Document> coll = mongoDatabase
				.getCollection(collection);
		return coll.find(new Document("id", id)).first();
	}

	// 查询列表
	public static MongoCursor<Document> findByPage(MongoDatabase mongoDatabase, String collection, 
			Map<String, Object> conditions, String orderByField,String orderByValue,int pageNo, int pageSize) {
		MongoCollection<Document> coll = mongoDatabase.getCollection(collection);
		
		BasicDBObject queryObject = new BasicDBObject();
		Iterator iter = conditions.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object field = entry.getKey();
			Object value = entry.getValue();
			queryObject.append(QueryOperators.AND,new BasicDBObject[] { new BasicDBObject(field.toString(), value) });
		}
		
		Bson orderBy = null;
		//-1 倒序
		if(orderByValue.equals("desc")) {
			orderBy = new BasicDBObject(orderByField, -1);
		}else if(orderByValue.equals("asc")) {
			orderBy = new BasicDBObject(orderByField, 1);
		}
		return coll.find(queryObject).sort(orderBy).skip((pageNo - 1) * pageSize)
				.limit(pageSize).iterator();
	}
	
	// 查询总数
	public static Long findByCount(MongoDatabase mongoDatabase, String collection, 
			Map<String, Object> conditions) {
		MongoCollection<Document> coll = mongoDatabase.getCollection(collection);
		BasicDBObject queryObject = new BasicDBObject();
		Iterator iter = conditions.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object field = entry.getKey();
			Object value = entry.getValue();
			queryObject.append(QueryOperators.AND,new BasicDBObject[] { new BasicDBObject(field.toString(), value) });
		}
		return coll.count(queryObject);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		MongoDatabase mongoDatabase = getMongoDatabaseConnection(
				"127.0.0.1", 27017, "test");
		System.out.println(mongoDatabase);

		// 单个新增
		IdWorker worker2 = new IdWorker(2);
		Document document = new Document();
		document.put("id", String.valueOf(worker2.nextId()));
		document.put("title", "计算机机器人99");
		document.put("author", "张三99、李四99、王五99");
		document.put("status", "0");
		document.put("create_time", new Date());
		insertOne(mongoDatabase, "hymax_date", document);

		// 单个查询
		Map<String, Object> aDocument = find(mongoDatabase, "hymax_date",
				"3588752262383616");
		// aDocument.remove("_id");
		System.out.println(aDocument);
		System.out.println(aDocument.get("id") + "/" + aDocument.get("title"));

		// 批量更新
		// Map<String,Object> conditions = new HashMap<String, Object>();
		// conditions.put("status", "1");
		// Map<String, Object> dynamicData = new HashMap<String, Object>();
		// dynamicData.put("title", "机智的小安");
		// edit(mongoDatabase, "hymax_test", conditions, dynamicData);
		/*
		 * Map<String,Object> dynamicData = new HashMap<String, Object>();
		 * dynamicData.put("title", "计算机机器人999"); dynamicData.put("status",
		 * "0"); editByIds(mongoDatabase, "hymax_date", new
		 * String[]{"3588579275786240","3588579849095168","3588580054386688"},
		 * dynamicData);
		 */

		// 单个更新
		// Map<String, Object> dynamicData = new HashMap<String, Object>();
		// dynamicData.put("title", "断魂谷那个头");
		// dynamicData.put("keywords", "口才;计算机人才");
		// edit(mongoDatabase, "hymax_test", "3551047290472448", dynamicData);

		// 单个删除
		// delete(mongoDatabase, "hymax_test", "3551047290472448");

		// 批量删除
		// Map<String,Object> conditions = new HashMap<String, Object>();
		// conditions.put("status", "1");
		// delete(mongoDatabase, "hymax_test", conditions);
		
		//遍历结果集
		// MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();
        // while (cursor1.hasNext()) {
        // org.bson.Document _doc = (Document) cursor1.next();
        // System.out.println(_doc.toString());
        // }

		closeConnection();
	}

}
